import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:ty_smart_watch/bean/alarm_bean.dart';
import 'package:ty_smart_watch/bean/receive_data_bean.dart';
import 'package:ty_smart_watch/ble/ble_util.dart';
import 'package:ty_smart_watch/common/function_id.dart';
import 'package:ty_smart_watch/utils/Log.dart';

class WatchSettingController extends GetxController {
  //整体数据更新
  Rx<ReceiveDataBean> receiveDataBean = ReceiveDataBean(-1, -1, -1, -1, -1, -1, -1).obs;

  //TimeRangeBean
  Rx<TimeRangeBean> timeRangeBean = TimeRangeBean(false, 0, 0, 0, 0, 0).obs;
  Rx<MedicineRemindBean> medicineRemindBean = MedicineRemindBean(false, 0, 0).obs;
  Rx<PeriodBean> periodBean = PeriodBean(false, 0, 0, 0, 0).obs;
  Rx<StepTargetBean> stepTargetBean = StepTargetBean(0).obs;
  Rx<DoNotDisturbBean> doNotDisturbBean = DoNotDisturbBean(0, 0, 0, 0, 0).obs;

  // Rx<SosBean> sosBean = SosBean(0, 0, "").obs;
  Rx<List<SosBean>> sosList = Rx<List<SosBean>>([]);
  Rx<List<AlarmBean>> alarmList = Rx<List<AlarmBean>>([]);

  final int SOS_TYPE_NEW = 0;
  final int SOS_TYPE_DELETE = 2;
  final int SOS_TYPE_MODIFY = 1;

  //radio index 更新
  Rx<int> radioIndex = 9.obs;

  //是否关闭当前页面
  Rx<int> needClosePage = 0.obs;

  @override
  void onInit() {
    super.onInit();
    Log.d("on Init");
  }

  @override
  void onReady() {
    super.onReady();
    Log.d("on Ready");
  }

  @override
  void onClose() {
    super.onClose();
    Log.d("on Close");
  }

  //获取对应的信息
  getBleData(String mac, int functionId) {
    SmartDialog.showLoading(
      msg: "读取中",
      backDismiss: false,
      clickMaskDismiss: false,
      displayTime: const Duration(seconds: 5),
    );
    BleUtil.writeBleData(mac, BleUtil.makeWriteData(functionId: functionId));
  }

  //更新Bean
  updateDataBean(ReceiveDataBean bean) {
    Log.d("更新 bean 数据  >  $bean");
    receiveDataBean.value = bean;
    receiveDataBean.refresh();
    switch (bean.functionId) {
      case HOUR_TYPE:
        radioIndex(bean.dataLongMap['type']);
        break;
      case ANTI_LOST:
        radioIndex(bean.dataLongMap['switch']);
        break;
      case INCH_TYPE:
        radioIndex(bean.dataLongMap['inch']);
        break;
      case TEMPERATURE_TYPE:
        radioIndex(bean.dataLongMap['temperatureType']);
        break;
      case SHAKE:
        var level = bean.dataLongMap['level'];
        Log.d("更新bean Level = $level");
        radioIndex((level ?? 1) - 1);
        break;

      //"喝水提醒设置"
      case DRINK_REMIND:
      //"定时心率设置:
      case TIME_HEART:
      //"定时体温设置:
      case TIMING_BODY_TEMPERATURE:
      //"久坐提醒设置:
      case LONG_SIT:
        bool isSwitch = bean.dataLongMap["switch"] == 1;
        int startHour = bean.dataLongMap["startHour"] ?? 0;
        int startMinute = bean.dataLongMap["startMinute"] ?? 0;
        int endHour = bean.dataLongMap["endHour"] ?? 0;
        int endMinute = bean.dataLongMap["endMinute"] ?? 0;
        int duration = bean.dataLongMap["duration"] ?? 0;
        TimeRangeBean timeRangeBean =
            TimeRangeBean(isSwitch, startHour, startMinute, endHour, endMinute, duration);
        updateTimeRangeBean(timeRangeBean);
        break;
      case MEDICINE_REMIND:
        bool isSwitch = bean.dataLongMap["switch"] == 1;
        int hour = bean.dataLongMap["hour"] ?? 0;
        int minute = bean.dataLongMap["minute"] ?? 0;
        MedicineRemindBean medicineRemindBean = MedicineRemindBean(isSwitch, hour, minute);
        updateMedicineRemindBean(medicineRemindBean);
        break;
      case PERIOD:
        bool isSwitch = bean.dataLongMap["switch"] == 1;
        int year = bean.dataLongMap["year"] ?? 0;
        int month = bean.dataLongMap["month"] ?? 0;
        int day = bean.dataLongMap["day"] ?? 0;
        int duration = bean.dataLongMap["duration"] ?? 0;
        PeriodBean periodBean = PeriodBean(isSwitch, year, month, day, duration);
        updatePeriodBean(periodBean);
        break;
      case STEP_TARGET:
        int target = bean.dataLongMap["stepTarget"] ?? 0;
        StepTargetBean stepTargetBean = StepTargetBean(target);
        updateStepTargetBean(stepTargetBean);
        break;
      //"勿扰设置"
      case DO_NOT_DISTURB:
        int isSwitch = bean.dataLongMap["switch"] ?? 0;
        int startHour = bean.dataLongMap["startHour"] ?? 0;
        int startMinute = bean.dataLongMap["startMinute"] ?? 0;
        int endHour = bean.dataLongMap["endHour"] ?? 0;
        int endMinute = bean.dataLongMap["endMinute"] ?? 0;
        DoNotDisturbBean disturbBean =
            DoNotDisturbBean(isSwitch, startHour, startMinute, endHour, endMinute);
        updateDoNotDisturbBean(disturbBean);
        break;
      //sos
      case SOS:
        if (bean.dataLongMap.isEmpty) {
          //当前无SOS，加载空布局
          Log.d("当前无SOS联系人，加载空布局");
          break;
        } else {
          Log.d("存在SOS联系人");
          var sos = SosBean(bean.dataLongMap["id"] ?? 0, bean.dataStringMap["name"] ?? "",
              bean.dataStringMap["number"] ?? "");
          Log.d("sos 联系人 操作类型: ${(bean.dataLongMap["type"] ?? -1)}");
          Log.d("sos 联系人 是否存在: ${sosList.value.contains(sos)}");

          //收到的sos联系人类型为删除（0x02），且list中包含该联系人，则删除本地list中对应项
          if ((bean.dataLongMap["type"] ?? -1) == SOS_TYPE_DELETE && sosList.value.contains(sos)) {
            Log.d("删除联系人: ${sos.name}");
            var tempList = sosList.value;
            tempList.remove(sos);
            updateSosList(tempList);
          } else if ((bean.dataLongMap["type"] ?? -1) == SOS_TYPE_MODIFY) {
            //收到的sos联系人类型为修改（0x01），修改本地list中对应项
            Log.d("修改联系人:");
            var itemIndex = _findItemIndex(sos.id);
            Log.d("修改联系人 index : $itemIndex");
            var tempList = sosList.value;
            tempList[itemIndex] = sos;
            updateSosList(tempList);
          } else {
            //收到的sos联系人类型为新增（0x00），且list中不包含该联系人，则添加本地list中对应项
            Log.d("收到的sos联系人类型为新增 ");
            if (!sosList.value.contains(sos)) {
              Log.d("列表中无该人，应该添加: $sos");
              var tempList = sosList.value;
              tempList.add(sos);
              updateSosList(tempList);
            }
          }
          break;
        }
      //闹钟
      case ALARM:
        if (bean.dataLongMap.isEmpty) {
          //当前无闹钟，加载空布局
          Log.d("当前无闹钟，加载空布局");
          updateAlarmList([]);
          break;
        } else {
          List<AlarmBean> alarmList = bean.dataAlarmMap["alarm"]!;
          updateAlarmList(alarmList);
        }
        break;
    }
    SmartDialog.dismiss(status: SmartStatus.loading);
    if (needClosePage.value == 1) {
      updateNeedClosePage(2);
    }
  }

  /// RadioGroup类型页面使用
  /// 改变radio的index
  updateRadioIndex(int index) {
    radioIndex(index);
  }

  /// 时间范围通用Bean
  updateTimeRangeBean(TimeRangeBean bean) {
    timeRangeBean(bean);
    timeRangeBean.refresh();
  }

  /// 定时吃药提醒Bean
  updateMedicineRemindBean(MedicineRemindBean bean) {
    medicineRemindBean(bean);
    medicineRemindBean.refresh();
  }

  /// 生理期提醒Bean
  updatePeriodBean(PeriodBean bean) {
    periodBean(bean);
    periodBean.refresh();
  }

  /// 计步目标Bean
  updateStepTargetBean(StepTargetBean bean) {
    stepTargetBean(bean);
    stepTargetBean.refresh();
  }

  /// 勿扰模式Bean
  updateDoNotDisturbBean(DoNotDisturbBean bean) {
    doNotDisturbBean(bean);
    doNotDisturbBean.refresh();
  }

  /// Sos List
  updateSosList(List<SosBean> list) {
    sosList(list);
    sosList.refresh();
  }

  /// Alarm List
  updateAlarmList(List<AlarmBean> list) {
    alarmList(list);
    alarmList.refresh();
  }

  ///决定是否关闭当前页面
  updateNeedClosePage(int i) {
    needClosePage(i);
  }

  int _findItemIndex(int id) {
    var temp = sosList.value;
    int res = -1;
    for (int i = 0; i < temp.length; i++) {
      if (temp[i].id == id) {
        res = i;
        break;
      }
    }
    return res;
  }
}

class TimeRangeBean {
  bool isSwitch;
  int startHour;
  int startMinute;
  int endHour;
  int endMinute;
  int duration;

  TimeRangeBean(
      this.isSwitch, this.startHour, this.startMinute, this.endHour, this.endMinute, this.duration);
}

class DoNotDisturbBean {
  int isSwitch;
  int startHour;
  int startMinute;
  int endHour;
  int endMinute;

  DoNotDisturbBean(this.isSwitch, this.startHour, this.startMinute, this.endHour, this.endMinute);
}

class MedicineRemindBean {
  bool isSwitch;
  int hour;
  int minute;

  MedicineRemindBean(this.isSwitch, this.hour, this.minute);
}

class PeriodBean {
  bool isSwitch;
  int year;
  int month;
  int day;
  int duration;

  PeriodBean(this.isSwitch, this.year, this.month, this.day, this.duration);
}

class StepTargetBean {
  int stepTarget;

  StepTargetBean(this.stepTarget);
}

class SosBean {
  int id;
  String name;
  String phone;

  SosBean(this.id, this.name, this.phone);

  @override
  String toString() {
    return 'SosBean{id: $id, name: $name, phone: $phone}';
  }

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is SosBean && id == other.id && name == other.name && phone == other.phone;

  @override
  int get hashCode => id.hashCode ^ name.hashCode ^ phone.hashCode;
}
